const async = require('async');
const path = require('path');  
const mkdirp = require('mkdirp');
const _ = require('lodash');
const messageController = require('./controller/messageController');
const errorTip = require('./util/errorTip');
const messageCron = require('./cron/message');
const domain = require('domain');
const moment = require('moment');

const SetUp = {

	mountModules : function (app, server) {
		var self = this;
		
		//验证模块
		app.use(require('express-validator')(
			{
				//自定义验证组件传入的第一个参数是被验证的值，后边的值通过options传入
				customValidators: {
					isArray: function(value) {
						return Array.isArray(value);
					},
					gte: function(param, num) {
						return param >= num;
					}
				}
			}
		));
		
		//log模块
		switch(app.get('env')){
			case 'development':
				app.use(require('morgan')('dev'));
				break;
			case 'production':
				app.use(require('express-logger')({
				    path: __dirname + '/log/webService.log'
				}));
				break; 
		}

	    //post请求body解析器
		app.use(require('body-parser')());

		//连接数据库
		require('./dao/db');

		//连接redis
		require('./redis/redis');
	
	},

	registerController : function(app){
		let middleware = [];
		messageController.registerAll(app, middleware);
	},

	error404 : function(app){
		app.use(function(req, res, next){ 
			res.status(404).json({ code: 1, status: 404, data: errorTip['请求访问的资源不存在'] });
		});
	},

	error500 : function(app){
		app.use(function(err, req, res, next){ 
			console.error(err.stack);
		    res.status(500).json({ code: 1, status: 500, data: errorTip['服务器内部错误'] });
		});
	},

    handleUncaughtException : function (app) {

        app.use((req, res, next) => {

            let d = domain.create();

            res.once('finish', () => {
                d.exit();
                d.removeAllListeners();
            });

            d.once('error', (err) => {
                if (!res.headersSent) {
                    res.status(500).json({ code: 1, status: 500, data: errorTip['服务器内部错误'] });
                }
                console.error(`DOMAIN ERROR CAUGHT AT ${moment().format('YYYY-MM-DD hh:mm:ss')}\n`, err.stack || err);
                d.exit();
                d.removeAllListeners();
            });

            d.run(next);

        });
    },
	
	initCron: function(){
		// messageCron.initJob();
	}
};

module.exports = SetUp;